package com.example.api.service.impl;


import com.example.api.exception.BusException;
import com.example.api.exception.ParamException;
import com.example.api.mapper.BookDetailMapper;
import com.example.api.pojo.BookDetail;
import com.example.api.pojo.Customer;
import com.example.api.service.AddressService;
import com.example.api.service.CartService;
import com.example.api.service.CustomerService;
import com.example.api.utils.CartItem;
import com.example.api.utils.ThreadContextUtil;
import com.example.api.vo.AddressVO;
import com.example.api.vo.BookVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.example.api.constant.BookConst;
import com.example.api.mapper.BookMapper;
import com.example.api.pojo.Book;
import com.example.api.query.BookQuery;
import com.example.api.service.BookService;
import com.example.api.utils.PageResult;
import com.example.api.vo.BookListVO;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BookServiceImpl implements BookService {


    @Resource
    BookMapper bookMapper;

    @Resource
    CartService cartService;

    @Resource
    AddressService addressService;

    @Resource
    BookDetailMapper bookDetailMapper;

    @Resource
    CustomerService customerService;




    @Override
    public PageResult<BookListVO> find(BookQuery bookQuery) {
        //设置是否需要分页
        PageHelper.startPage(bookQuery.getPage(), bookQuery.getPageSize());

        Page<BookListVO> page = (Page<BookListVO>) bookMapper.find(bookQuery);
        PageInfo<BookListVO> pageInfo = page.toPageInfo();


        List<BookListVO> bookListVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        PageResult<BookListVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setList(bookListVOList);

        return pageResult;
    }

    @Override
    public BookVO findByNum(String num) {
        return bookMapper.findByNum(num);
    }


    @Override
    public synchronized void receive(String num) {

        byte status = bookMapper.findStatus(num);
        if (status != BookConst.PENDING_CONFIRMED) {
            throw new BusException("状态错误,不能执行接单操作");
        }

        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.RECEIVED);  //已接单
        bookMapper.update(book);
    }

    @Override
    public synchronized void reject(String num, String rejectionReason) {
        byte status = bookMapper.findStatus(num);
        if (status != BookConst.PENDING_CONFIRMED) {
            throw new BusException("状态错误,不能执行接单操作");
        }

        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.REFUNDED); //设置退款状态
        book.setRejectionReason(rejectionReason);
        book.setCancelTime(new Date());

        bookMapper.update(book);
    }

    @Override
    public synchronized void delivery(String num) {
        byte status = bookMapper.findStatus(num);
        if (status != BookConst.RECEIVED) {
            throw new BusException("状态错误,不能执行派送操作");
        }

        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.DELIVERING);
        bookMapper.update(book);
    }

    @Override
    public synchronized void complete(String num) {

        byte status = bookMapper.findStatus(num);
        if (status != BookConst.DELIVERING) {
            throw new BusException("状态错误,不能执行完成操作");
        }

        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.COMPLETED);  //已经完成
        book.setDeliveryTime(new Date());
        bookMapper.update(book);
    }

//    @Override
//    public void cancel(String num, String cancelReason) {
//
//        //TODO
//        //判断当前订单是否已经支付，如果已经支付则需要退款
//
//        Book book = new Book();
//        book.setNum(num);
//        book.setStatus(BookConst.CANCELLED); //设置已取消状态
//        book.setCancelReason(cancelReason);
//        book.setCancelTime(new Date());
//        bookMapper.update(book);
//    }

    @Override
    public Map<String, Object> add(long addressId, String remark) {
        AddressVO addressVO = addressService.findById(addressId);
        if (addressVO == null) {
            throw new ParamException("收获地址参数异常");
        }

        List<CartItem> cartItemList = cartService.find();
        if (cartItemList == null || cartItemList.isEmpty()) {
            throw new BusException("购物车为空");
        }

        Long customerId = ThreadContextUtil.getData();


        Book book = new Book();

        BigDecimal bookAmount = new BigDecimal("0");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String num = simpleDateFormat.format(new Date()) + customerId;
        book.setNum(num);

        // book.setAmount(??);

        book.setCustomerId(customerId);

        Customer customer = customerService.findCustomerById(customerId);


        book.setCustomerName(customer.getName());  //TODO

        book.setCreateTime(new Date());
        book.setStatus(BookConst.PENDING_PAYMENT);

        book.setRemark(remark);

        book.setAddressId(addressId);


        book.setAddress(addressVO.getDetail());
        book.setPhone(addressVO.getPhone());
        book.setConsignee(addressVO.getConsignee());


        List<BookDetail> bookDetailList = new ArrayList<>();

        for (CartItem cartItem : cartItemList) {
            BookDetail bookDetail = new BookDetail();
            bookDetail.setBookNum(num);
            bookDetail.setFoodId(cartItem.getFoodId());
            bookDetail.setName(cartItem.getName());
            bookDetail.setPhoto(cartItem.getPhoto());

            bookDetail.setFoodFlavor(cartItem.getFlavorItem()+":"+cartItem.getFlavorValue());

            bookDetail.setTotal(cartItem.getCount());

            BigDecimal price = cartItem.getPrice();
            BigDecimal amount = price.multiply(new BigDecimal(cartItem.getCount() + ""));

            bookAmount = bookAmount.add(amount);

            bookDetail.setAmount(amount);
            bookDetailList.add(bookDetail);
        }

        book.setAmount(bookAmount);

        bookMapper.add(book);

        bookDetailMapper.addBatch(bookDetailList);


        Map<String,Object> result = new HashMap<>();
        result.put("num",num);
        result.put("amount",bookAmount.toString());
        return result;
    }

    @Override
    public Book findOrderByNum(String num) {
        return bookMapper.findOrderByNum(num);
    }

    @Override
    public void updatePaySuccess(String num, String payWay) {
        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.PENDING_CONFIRMED);
        book.setPayStatus(BookConst.PAID);
        book.setPayMethod("zfb".equals(payWay)?BookConst.PAY_ZFB:BookConst.PAY_WX);
        book.setPayTime(new Date());
        bookMapper.update(book);
    }

    @Override
    public PageResult<BookVO> findApp(BookQuery bookQuery) {
        //设置是否需要分页
        PageHelper.startPage(bookQuery.getPage(),bookQuery.getPageSize());

        PageResult<BookVO> pageResult = new PageResult<>();


        Page<BookVO> page = (Page<BookVO>) bookMapper.findApp(bookQuery);
        PageInfo<BookVO> pageInfo = page.toPageInfo();

        List<BookVO> bookListVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        pageResult.setTotal(total);
        pageResult.setList(bookListVOList);

        return pageResult;
    }


    @Override
    public void cancel(String num, String cancelReason) {
        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.CANCELLED); //设置已取消状态
        book.setCancelReason(cancelReason);
        book.setCancelTime(new Date());
        bookMapper.update(book);
    }
}